package com.example.educationcommunity.controller;

import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.User;
import com.example.educationcommunity.model.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@Controller
public class loginController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/login")
    private String login(){
        return "login";
    }
    @PostMapping("/login")
    private String doLogin(@RequestParam(name = "username") String username,
                           @RequestParam(name = "password") String password,
                           HttpServletResponse response,
                           Model model){
        model.addAttribute(username);
        model.addAttribute(password);
        if(username==null || username=="")
        {
            model.addAttribute("error","用户名不能为空");
            return "login";
        }
        if(password==null || password == "")
        {
            model.addAttribute("error","密码不能为空");
            return "login";
        }
        UserExample example = new UserExample();
        example.createCriteria()
                .andAccountIdEqualTo(username)
                .andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(example);
        if(users.size() == 0)
        {
            model.addAttribute("error","用户名或密码错误");
            return "login";
        }
        User dbUser = users.get(0);
        User upadteUser = new User();
        upadteUser.setGmtModified(System.currentTimeMillis());
        String token = UUID.randomUUID().toString();
        upadteUser.setToken(token);
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andIdEqualTo(dbUser.getId());
        userMapper.updateByExampleSelective(upadteUser, userExample);
        response.addCookie(new Cookie("token",token));
        return "redirect:/";
    }
}
